<?php
/**
 * +----------------------------------------------------------------------
 * | [ DO WHAT YOU LOVE AND FUCK THE REST ]
 * +----------------------------------------------------------------------
 * | EMAIL: < 931274989@qq.com >
 * +----------------------------------------------------------------------
 * | WECHAT: xzc016
 * +----------------------------------------------------------------------
 * | 系统
 * +----------------------------------------------------------------------
 */
namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\AuthGroup;
use app\admin\model\AuthGroupAccess;
use app\admin\model\AuthRule;
use app\admin\model\Base as BaseMode;
use app\admin\validate\Rule as RuleValidate;
use app\admin\validate\Group as GroupValidate;
use app\admin\validate\Admin as AdminValidate;

use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use think\Exception;

class Auth extends Base
{
  /*-----------------------用户组管理----------------------*/
  // 用户组管理
  public function adminGroup(){

    $model = new AuthGroup();

    $post = $this->request->param();
    if (isset($post['title']) and !empty($post['title'])) {
      $where[] = ['title', 'like', '%'.$post['title'].'%'];
    }

    if(isset($post['create_time']) and !empty($post['create_time'])) {
      $min_time = strtotime($post['create_time']);
      $max_time = $min_time + 24 * 60 * 60;
      $where[] = ['create_time','between',[$min_time,$max_time]];
    }

    $group = empty($where) ? $model->order('create_time desc')->paginate(Config::get('basic.page_size')) : $model->where($where)->order('create_time desc')->paginate(Config::get('basic.page_size'),false,['query'=>request()->get()]);
    View::assign('group',$group);
    return View::fetch('admin_group');
  }

  // 用户组添加/修改
  public function groupAdd(){
    //获取角色id
    $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
    if($id > 0) {
      //是修改操作
      if(Request::isPost()) {
        //是提交操作
        $post = Request::post();
        //验证
        (new GroupValidate())->goCheck();
        //处理选中的权限菜单id，转为字符串
        if(!empty($post['auth_rule_id'])) {
          $post['rules'] = implode(',',$post['auth_rule_id']);
        } else {
          $post['rules'] = '0';
        }
        unset($post['auth_rule_id']);
        if(false == AuthGroup::where('id','=',$id)->update($post)) {
          return error('修改失败');
        } else {
          adminLog();//写入日志
          return success('修改角色信息成功','admin/auth/adminGroup');
        }
      } else {
        //非提交操作
        $group = AuthGroup::where('id',$id)->find();
        if(!empty($group['rules'])) {
          //将菜单id字符串拆分成数组
          $group['rules'] = explode(',', $group['rules']);
        }
        $authRule = AuthRule::order('sort asc')->select()->toArray();
        $tree      = new \Tree();
        $info = $tree->list2tree($authRule);
        View::assign([
          'info'  => $info,
          'group' => $group
        ]);
        return View::fetch();
      }
    } else {
      //是新增操作
      if($this->request->isPost()) {
        //是提交操作
        $post = $this->request->post();
        //验证
        (new GroupValidate())->goCheck();
        //处理选中的权限菜单id，转为字符串
        if(!empty($post['auth_rule_id'])) {
          $post['rules'] = implode(',',$post['auth_rule_id']);
        }
        if(false == AuthGroup::create($post)) {
          return error('添加角色失败');
        } else {
          adminLog();//写入日志
          return success('添加角色成功','admin/auth/adminGroup');
        }
      } else {
        //非提交操作
        $authRule = AuthRule::order('sort asc')->select()->toArray();
        $tree      = new \Tree();
        $info = $tree->list2tree($authRule);
        View::assign('info',$info);
        return View::fetch();
      }
    }
  }

  // 用户组删除
  public function groupDel(){
    $id = Request::param('id');
    if ($id==1) {
      return error('超级管理员组不可删除!');
    }else{
      Db::startTrans();
      try {
        AuthGroup::destroy($id);
        AuthGroupAccess::where('group_id', '=', $id)->delete();
        Db::commit();
        adminLog(); //写入日志
        return success('删除成功！');
      } catch (Exception $e) {
        Db::rollback();
        Log::error($e);
        return error('删除失败！');
      }
    }
  }

  // 用户组状态修改
  public function groupState(){
    if (Request::isPost()) {
      $id = Request::param('id');
      $info = AuthGroup::find($id);
      $info->status = Request::param('status');
      $info->save();
      adminLog(); // 写入日志
      return success('修改成功!');
    }
  }

  // 权限预览
  public function seeRule() {
    $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
    $group = AuthGroup::where('id',$id)->find();
    if(!empty($group['rules'])) {
      //将菜单id字符串拆分成数组
      $group['rules'] = explode(',', $group['rules']);
    }
    $authRule = AuthRule::order('sort asc')->select()->toArray();
    $tree      = new \Tree();
    $info = $tree->list2tree($authRule);
    View::assign([
      'info'  => $info,
      'group' => $group
    ]);
    return View::fetch();
  }

  /*-----------------------管理员管理----------------------*/
  // 管理员列表
  public function adminList()
  {
    $model = new Admin();

    $post = $this->request->param();
    if (isset($post['title']) and !empty($post['title'])) {
      $where[] = ['username', 'like', '%'.$post['title'].'%'];
    }

    if(isset($post['create_time']) and !empty($post['create_time'])) {
      $min_time = strtotime($post['create_time']);
      $max_time = $min_time + 24 * 60 * 60;
      $where[] = ['create_time','between',[$min_time,$max_time]];
    }

    if(isset($post['group']) and !empty($post['group'])) {
      $uid = AuthGroupAccess::where('group_id',$post['group'])->column('uid');
      $where[] = ['id' , 'in' , $uid];
    }
    
    $admin = empty($where) ? $model->order('create_time desc')->paginate(Config::get('basic.page_size')) : $model->where($where)->order('create_time desc')->paginate(Config::get('basic.page_size'),false,['query'=>request()->get()]);
    $info['group'] = AuthGroup::select();
    View::assign([
      'admin' => $admin,
      'info'  => $info
    ]);
    return View::fetch();
  }

  // 管理员添加/修改
  public function adminAdd(){
    $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
    if ($id > 0) {
      //是修改操作
      if(Request::isPost()) {
        (new AdminValidate())->goCheck();
        $data = Request::post();
        $group_id = $data['group_id'];
        unset($data['group_id']);
        Db::startTrans();
        try {
          Admin::update($data, ['id' =>  $id]); 
          AuthGroupAccess::update([ 'group_id' =>  $group_id], ['uid' =>  $id]);
          Db::commit();
          adminLog(); //写入日志
          return success('管理员修改成功', 'adminList');
        } catch (Exception $e) {
          Db::rollback();
          Log::error($e);
          return error('管理员添加失败');
        }
      } else {
        $menu = Admin::where('id', '=', $id)->find();
        $auth_group = AuthGroup::where('status','=',1)
          ->select();
        View::assign([
          'menu' => $menu,
          'authGroup' => $auth_group,
        ]);
        return View::fetch('admin_add');
      }
    }
    else {
      // 新增操作
      if (Request::isPost()) {
        $data = Request::post();
        //验证
        (new AdminValidate())->goCheck();
        $group_id = $data['group_id'];
        $data['password']  = password(Config::get('admin.password'));  // 默认密码123456
        $data['image']  = '\uploads\admin\admin_img\20200301\3fc248269fbf02d9730e0e7dc23dff90.jpg';
        $data['status']    = 1;
        unset($data['group_id']);
        //添加
        Db::startTrans();
        try  {
          $result = Admin::create($data);
          AuthGroupAccess::create([
            'uid'      =>  $result->id,
            'group_id' =>  $group_id
          ]);
          Db::commit();
          adminLog(); //写入日志
          return success('管理员添加成功', 'adminList');
        } catch  (Exception $e) {
          Db::rollback();
          Log::error($e);
          return error('管理员添加失败');
        }
      } else {
        $auth_group = AuthGroup::where('status','=',1)
          ->select();
        View::assign(['authGroup' => $auth_group]);
        return View::fetch('admin_add');
      }
    }
  }

  // 管理员删除
  public function adminDel(){
    $id = Request::param('id');
    if ($id) {
      Db::startTrans();
      try {
        Admin::destroy($id);
        AuthGroupAccess::where('uid', '=', $id)->delete();
        Db::commit();
        adminLog();  // 写入日志
        return success('删除成功!');
      } catch (Exception $e) {
        Db::rollback();
        return error('删除失败');
      }
    } else {
      return error('id错误');
    }
  }

  // 管理员批量删除
  public function adminSelectDel(){
    $ids = Request::param('ids');
    if (is_array($ids)) {
      Db::startTrans();
      try {
        Admin::destroy($ids);
        AuthGroupAccess::where('uid', 'in', $ids)->delete();
        Db::commit();
        adminLog(); // 写入日志
        return success('删除成功!');
      } catch (Exception $e) {
        Db::rollback();
        return error('删除失败！');
      }
    }
    else {
      return error('id错误！');
    }
  }

  // 管理员状态修改
  public function adminState(){
    $id = Request::param('id');
    if(!empty($id)) {
      $admin = Admin::find($id);
      $admin->status = Request::param('status');
      $admin->save();
      adminLog(); //写入日志
      return success('修改成功！');
    } 
    else {
      return error('用户ID不存在!');
    }
  }

  // 重置密码
  public function ResetPassword() {
    $id = Request::param('id');
    if(!empty($id)) {
      $admin = Admin::find($id);
      $admin->password = password(Config::get('admin.password'));
      $admin->save();
      adminLog(); //写入日志
      return success('重置成功！');
    }
    else {
      return error('用户ID不存在!');
    }
  }

  
  /*-----------------------系统菜单管理-----------------------*/
  // 系统菜单列表
  public function adminRule() {
    $menu = AuthRule::order('sort asc')->select()->toArray();
    $tree      = new \Tree();
    $menus = $tree->array2tree($menu);
    View::assign('menus',$menus);
    return View::fetch();
  }
  
  // 系统菜单添加修改
  public function ruleAdd() {
    //获取菜单id
    $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
    $model = new AuthRule();
    //是正常添加操作
    if($id > 0) {
      //是修改操作
      if($this->request->isPost()) {
        //是提交操作
        $post = $this->request->post();
        //验证  
        (new RuleValidate())->goCheck();
        //验证菜单是否存在
        $menu = $model->find($id);
        if(empty($menu)) return error('id不正确');

        $post['status'] = empty($post['status']) ? 0 : $post['status'];
        $post['type'] = empty($post['type']) ? 0 : $post['type'];

        $result = $model->where('id',$id)->save($post);
        if(!$result) {
          return error('修改失败');
        } else {
          adminLog();//写入日志
          return success('修改菜单信息成功','admin/Auth/adminRule');
        }
      } else {
        //非提交操作
        $menu = $model->where('id',$id)->find();
        $menus = $model->select();
        $menus_all = $model->menuList($menus);
        View::assign('menus',$menus_all);
        if(!empty($menu)) {
          View::assign('menu',$menu);
          return View::fetch();
        } else {
          return error('id不正确');
        }
      }
    } else {
      //是新增操作
      if($this->request->isPost()) {
        //是提交操作
        $post = $this->request->post();
        //验证  
        (new RuleValidate())->goCheck();
        if(false == $model->save($post)) {
          return $this->error('添加菜单失败');
        } else {
          adminLog(); //写入日志
          return success('添加菜单成功','admin/Auth/adminRule');
        }
      } else {
        //非提交操作
        $pid = $this->request->has('pid') ? $this->request->param('pid', null, 'intval') : null;
        if(!empty($pid)) {
          View::assign('pid',$pid);
        }
        $menu = $model->select();
        $menus = $model->menuList($menu);
        View::assign('menus',$menus);
        return View::fetch();
      }
    }
  }

  // 系统菜单删除
  public function ruleDel() {
    if($this->request->isAjax()) {
      $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
      $result = Db::name('auth_rule')->where('pid',$id)->select();
      if($result->isEmpty()) {
        Db::startTrans();
        try {
          $rules = AuthGroup::column('rules');
          $ids = AuthGroup::column('id');
          $group = "";
          foreach($rules as $k => $val) {
            $rule = explode(",",$val);
            if (in_array($id,$rule)) {
              $values = implode(',',array_diff($rule, [$id]));
              $group = AuthGroup::update(['rules' => $values], ['id' => $ids[$k]]);
            }
          }
          AuthRule::destroy($id);
          Db::commit();
          adminLog();//写入日志
          return success('删除成功','admin/Auth/adminRule');
        } catch (Exception $e) {
          Db::rollback();
          return error('删除失败');
        };
      } else {
        return error('该菜单下还有子菜单，不能删除');
      }
    }
  }

  // 左侧菜单栏显示隐藏状态修改
  public function authOpen(){
    $id = Request::param('id');
    if(!empty($id)) {
      $AuthRule = AuthRule::find($id);
      $AuthRule->auth_open = Request::param('auth_open');
      $AuthRule->save();
      adminLog(); //写入日志
      return success('修改成功！');
    } 
    else {
      return error('ID不存在!');
    }
  }

  // 系统菜单排序
  public function ruleSort(){
    if($this->request->isPost()) {
      $post = $this->request->post();
      $i = 0;
      foreach ($post['id'] as $k => $val) {
        $sort = Db::name('auth_rule')->where('id',$val)->value('sort');
        if($sort != $post['sort'][$k]) {
          if(false == Db::name('auth_rule')->where('id',$val)->update(['sort'=>$post['sort'][$k]])) {
            return error('更新失败');
          } else {
            $i++;
          }
        }
      }
      adminLog();//写入日志
      return success('成功更新'.$i.'个数据','admin/Auth/adminRule');
    }
  }


}
